#pragma once
#include <thread>
#include "EventLoop.hpp"
#include "WorkThread.hpp"
#include <stdbool.h>
#include <vector>
#include <assert.h>

using namespace std;
// 定义线程池的结构体
class ThreadPool
{
public:
    ThreadPool(class EventLoop *mainLoop, int count)
    {
        m_index = 0;
        m_isStart = false;
        m_mainLoop = mainLoop;
        m_threadNum = count;
        m_WorkerThreads.clear();
    }
    ~ThreadPool()
    {
        for (auto item : m_WorkerThreads)
        {
            delete item;
        }
    }

    // 启动线程池
    void run()
    {
        assert(!m_isStart);
        if (m_mainLoop->getThreadID() != this_thread::get_id())
        {
            exit(0);
        }
        m_isStart = true;
        if (m_threadNum > 0)
        {
            for (int i = 0; i < m_threadNum; ++i)
            {
                WorkerThread *subThread = new WorkerThread(i);
                subThread->run();
                m_WorkerThreads.push_back(subThread);
            }
        }
    }

    // 取出线程池中的某一个子线程的反应堆实例
    EventLoop *takeWorkerEventLoop()
    {
        assert(m_isStart);
        if (m_mainLoop->getThreadID() != this_thread::get_id())
        {
            exit(0);
        }
        // 让主线程从线程池中找出一个子线程，取出里面的eventloop实例
        // 如果线程池中没有子线程，就使用主线程
        class EventLoop *evLoop = m_mainLoop;
        if (m_threadNum > 0)
        {
            evLoop = m_WorkerThreads[m_index]->getEventLoop();
            m_index = ++m_index % m_threadNum;
        }
        return evLoop;
    }

private:
    // 主线程的反应堆模型
    class EventLoop *m_mainLoop;
    bool m_isStart;
    vector<WorkerThread *> m_WorkerThreads;
    int m_threadNum;
    int m_index;
};
